// ~ Package Declaration
// ==================================================

package com.wms.web.action.system;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.ExceptionMappings;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.wms.data.WmsFrameworkException;
import com.wms.data.domain.service.SystemUserService;
import com.wms.data.pojo.SystemUser;
import com.wms.utils.ADVerification;
import com.wms.web.action.AbstractAction;

//~ Comments
//==================================================

/**
 * Login Action.
 * 
 * <table border="1" width="80%">
 * <tr>
 * <th>Version</th>
 * <th>Date</th>
 * <th>Role</th>
 * <th>Modified By</th>
 * <th>Details</th>
 * </tr>
 * <tr>
 * <td>%I%</td>
 * <td>2011/11/18</td>
 * <td>SD/PG</td>
 * <td>Evan</td>
 * <td>Created By</td>
 * </tr>
 * </table>
 * <p/>
 * 
 * <pre>
 *	PSTS Pooling Action.
 * </pre>
 *
 * @author Evan
 * @version 1.0
 * @since 1.5
 * 
 * SVN:
 * <ol>
 * 	<li>$Id$</li>
 * 	<li>$Rev$</li>
 * </ol>
 *
 */
@ParentPackage("wms")
@Namespace("/app")
@Result(name="exception", location="/WEB-INF/jsp/common/error.jsp")
@ExceptionMappings(@ExceptionMapping(exception="java.lang.Exception", result="exception"))
public class LoginAction extends AbstractAction {

	//~ Static Fields
	// ==================================================
	
	private static final long serialVersionUID = 1L;
	
	// ~ Fields
	// ==================================================
	
	@Autowired
	private SystemUserService systemUserService;
	
	private String userName;
	
	private String password;
	
	private String verifycode;
	
	private boolean adLogin;
	
	//~ Constructors
	// ==================================================

	// ~ Methods
	// ==================================================
	
	/**
	 * init Login.
	 *
	 * <pre>
	 * 	init Login
	 * </pre>
	 *
	 * @return String
	 */
	@Action(value="initLogin", interceptorRefs={@InterceptorRef(value="defaultStack")})
	public String initLogin() {
		
		return LoginAction.LOGIN;
	}
	
	/**
	 * User Login.
	 *
	 * <pre>
	 * 	User Login
	 * </pre>
	 *
	 * @return String
	 */
	@Action(value="login", results={@Result(name="success", location="/WEB-INF/jsp/system/main/main.jsp")}, 
					interceptorRefs={@InterceptorRef(value="defaultStack")})
	public String login() {
		
		try {
			
			// 验证码
			Object oVerifycode = (String) getSessionMap().get("verifycode");
			
			if (StringUtils.isBlank(this.getUserName()) || StringUtils.isEmpty(this.getPassword()) || oVerifycode == null) {
				
				return LOGIN;
			}
			else {
				
				String verifycode = (String) oVerifycode;
				
				if (StringUtils.isBlank(verifycode)) {
					
					return LOGIN;
				}
				
				if (StringUtils.equalsIgnoreCase(verifycode, getVerifycode())) {
					
					return login4DB();
				}
				else {
					
					throw new WmsFrameworkException("验证码错误，请重新输入！");
				}
			}
		}
		catch (WmsFrameworkException wfe) {
			
			setMessageCode(wfe.getMessage());
			
			return LoginAction.LOGIN;
		}
		catch (Exception e) {
			e.printStackTrace();
			setMessageCode("UF-1001.login.message.login.fail");
			
			return LOGIN;
		}
	}
	
	private String login4DB() throws Exception {
		
		SystemUser user = systemUserService.updateLogin(userName, password, 1, getRemoteAddr());
		
		if (user != null) {
			
			setLoginUser(user);
		}
		else {
			
			setLoginUser(null);
			
			throw new WmsFrameworkException("UF-1001.login.message.login.passwrodError");
		}
		
		return SUCCESS;
	}
	
	@SuppressWarnings("unused")
	private String login4AD() throws Exception {
	
		ADVerification adVerification = new ADVerification();
		String loginResult = adVerification.verifyUserLogin(this.getUserName(), this.getPassword());
		
		if (StringUtils.equals(ADVerification.LOGIN_MSG_SUCCESS, loginResult) || !getAdLogin()) {
			
			// Read user information from the DB.
//			SystemUser sysUser = pstsUserService.findUserByUserName(getUserName());
			SystemUser sysUser = null;
			
			if (sysUser != null) {
			
				Map<String, String> userFunctionMap = new HashMap<String, String>();
				Map<String, String> userUrlMap = new HashMap<String, String>();
				
				/*
				List<Map<String, String>> lstFunAndUrl = pstsMenuItemService.findFunAndURLListByUserName(getUserName());
				
				for (Map<String, String> funAndUrlMap : lstFunAndUrl) {
					
					userFunctionMap.put(funAndUrlMap.get(PstsMenuItem.MENU_KEY_CODE), funAndUrlMap.get(PstsMenuItem.MENU_KEY_CODE));
					userUrlMap.put(funAndUrlMap.get(PstsMenuItem.MENU_KEY_URL), funAndUrlMap.get(PstsMenuItem.MENU_KEY_URL));
				}
				
				getSessionMap().put(PstsUser.FUNCTION_SESSION_CODE, userFunctionMap);
				getSessionMap().put(PstsUser.URL_SESSION_CODE, userUrlMap);
				getSessionMap().put(PstsUser.MENU_SESSION_CODE, pstsMenuItemService.findListByUserName(getUserName()));*/
				
				this.setLoginUser(sysUser);
				
				return LoginAction.SUCCESS;
			}
			else {
				
				setMessageCode("PSTS.LOGIN.FAILED", ERROR);
				
				return LoginAction.LOGIN;
			}
			
		}
		else if (StringUtils.equals(ADVerification.LOGIN_MSG_FAILED, loginResult)) {
			
			// Login failed.
			this.setMessageCode("PSTS.LOGIN." + loginResult, ERROR);
			
			return LoginAction.LOGIN;
		}
		else {
			
			this.setMessageCode("PSTS.LOGIN." + loginResult, ERROR);
		}
		
		return LoginAction.LOGIN;
	}
	
	/**
	 * User Logout.
	 *
	 * <pre>
	 * 	User Logout
	 * </pre>
	 *
	 * @return String
	 */
	@Action(value="logout", results={@Result(name="login", location="/login.jsp")})
	public String logout() {
		
		this.setLoginUser(null);
		
		setMessageCode("PSTS.LOGOUT.LOGOUT");
		
		return LOGIN;
	}
	
	// 获取来源IP
	private String getRemoteAddr() {
		
		String remoteAddr = StringUtils.trimToEmpty(getRequest().getHeader("x-forwarded-for"));
		
		if (remoteAddr.length() == 0 || "unknown".equalsIgnoreCase(remoteAddr)) {
			remoteAddr = StringUtils.trimToEmpty(getRequest().getHeader("Proxy-Client-IP"));
		}
		
		if (remoteAddr.length() == 0 || "unknown".equalsIgnoreCase(remoteAddr)) {
			remoteAddr = StringUtils.trimToEmpty(getRequest().getHeader("WL-Proxy-Client-IP"));
		}
		
		if (remoteAddr.length() == 0 || "unknown".equalsIgnoreCase(remoteAddr)) {
			remoteAddr = StringUtils.trimToEmpty(getRequest().getRemoteAddr());
		}
		
		return remoteAddr;
	}

	/**
	 * @return the userName。
	 */
	public String getUserName() {
	
		return userName;
	}
	
	/**
	 * @param userName set userName。
	 */
	public void setUserName(String userName) {
	
		this.userName = userName;
	}
	
	/**
	 * @return the password。
	 */
	public String getPassword() {
	
		return password;
	}

	/**
	 * @param password set password。
	 */
	public void setPassword(String password) {
	
		this.password = password;
	}
	
  public String getVerifycode() {
  
  	return verifycode;
  }
	
  public void setVerifycode(String verifycode) {
  
  	this.verifycode = verifycode;
  }

	/**
	 * @return the adLogin。
	 */
	public boolean getAdLogin() {
	
		return adLogin;
	}

	/**
	 * @param adLogin set adLogin。
	 */
	public void setAdLogin(boolean adLogin) {
	
		this.adLogin = adLogin;
	}
}